package cn.mabach.portal.dianping.controller;

import cn.mabach.dianping.entity.CategoryEntity;

import cn.mabach.dianping.entity.ShopEntity;
import cn.mabach.portal.dianping.feign.CategoryServiceFeign;
import cn.mabach.portal.dianping.feign.ShopServiceFeign;
import cn.mabach.portal.dianping.mongo.Recs;
import cn.mabach.portal.dianping.mongo.Res;
import cn.mabach.portal.dianping.mongo.ShopTfIdf;
import cn.mabach.portal.dianping.mongo.WordInshop;
import cn.mabach.portal.utils.CookieUtils;
import cn.mabach.result.PageResult;
import cn.mabach.result.RS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: ming
 * @Date: 2020/2/28 0028 下午 8:20
 */
@Controller
@RequestMapping("/dianping")
@Slf4j
public class DianpingController {
    @Autowired
    private CategoryServiceFeign categoryServiceFeign;
    @Autowired
    private ShopServiceFeign shopServiceFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("/getCategory")
    @ResponseBody
    public RS getCategory(HttpServletRequest request,HttpServletResponse response,Model model){



        PageResult pageResult = categoryServiceFeign.queryPage( null,1,20);
        List<CategoryEntity> list = pageResult.getList();
        return RS.ok(list);
    }

    @RequestMapping("/recommend")
    @ResponseBody
    public RS recommend(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String uid = CookieUtils.getCookieValue(request, "SID");

        if (StringUtils.isEmpty(uid)){
            CookieUtils.setCookie(request,response,"SID", UUID.randomUUID().toString().replace("-",""),24*60*60*30*12);
            uid="default";
        }



        RS rs = shopServiceFeign.recommend(uid);


        return rs;
    }




    @RequestMapping("/search")
    @ResponseBody
    public Map search(@RequestParam(value = "longitude",required = false) BigDecimal longitude,
                     @RequestParam(value = "latitude",required = false) BigDecimal latitude,
                     @RequestParam("keyword") String keyword,
                     @RequestParam(value = "orderby",required = false)String orderby,
                     @RequestParam(value = "categoryId",required = false)Integer categoryId,
                     @RequestParam(value = "tags",required = false)String tags) throws IOException {
        Map<String, Object> map = shopServiceFeign.search(longitude, latitude, keyword, orderby, categoryId, tags);



        return map;

    }
    @RequestMapping("/shopfeatrue")
    @ResponseBody
    public RS shopfeatrue() {
        WordInshop byId = mongoTemplate.findById(18624, WordInshop.class);
        return RS.ok(byId);
    }

    @RequestMapping("/details")
    public String shopDetails(@RequestParam("id") Integer id,Model model,HttpServletRequest request){
        String jsessionid = CookieUtils.getCookieValue(request, "SID");

        model.addAttribute("id",id);
        log.warn("aclog_ "+jsessionid+" click "+id);
        ShopEntity byIdE = shopServiceFeign.getByIdE(id);
        model.addAttribute("name",byIdE.getName()+"  :  "+byIdE.getHot());


        Res res = mongoTemplate.findById(id, Res.class);
        List<Recs> recs = res.getRecs();


//        对list排序

        Collections.sort(recs, new Comparator<Recs>() {
            @Override
            public int compare(Recs o1, Recs o2) {
               Double score= o1.getScore() - o2.getScore();
//               返回>0返回1是升序
                if (score>0){
                    return -1;
                }
                if (score<0){
                    return 1;
                }
                return 0;
            }
        });


        log.info("========>展示相似度列表 "+recs);
        ArrayList<ShopEntity> shopEntities = new ArrayList<>();
//        取前5条
        if (recs.size()>=5){
            for (int i = 0; i < 5; i++) {
                Recs rec = recs.get(i);
                ShopEntity shopEntity = shopServiceFeign.getByIdE(rec.get_id());
                shopEntities.add(shopEntity);

            }
        }else {
            for (Recs rec : recs) {
                ShopEntity shopEntity = shopServiceFeign.getByIdE(rec.get_id());
                shopEntities.add(shopEntity);
            }

        }








        model.addAttribute("searchList",shopEntities);


        return "details.html";
    }

    @RequestMapping("/share")
    @ResponseBody
    public RS share(@RequestParam("id") String id,HttpServletRequest request){
        String jsessionid = CookieUtils.getCookieValue(request, "SID");


        log.warn("aclog_ "+jsessionid+" share "+id);


        return RS.ok();
    }

    @RequestMapping("/collect")
    @ResponseBody
    public RS collect(@RequestParam("id") String id,HttpServletRequest request){
        String jsessionid = CookieUtils.getCookieValue(request, "SID");


        log.warn("aclog_ "+jsessionid+" collect "+id);


        return RS.ok();
    }

    @RequestMapping("/buy")
    @ResponseBody
    public RS buy(@RequestParam("id") String id,HttpServletRequest request){
        String jsessionid = CookieUtils.getCookieValue(request, "SID");


        log.warn("aclog_ "+jsessionid+" buy "+id);


        return RS.ok();
    }

    @RequestMapping("/pay")
    @ResponseBody
    public RS pay(@RequestParam("id") String id,HttpServletRequest request){
        String jsessionid = CookieUtils.getCookieValue(request, "SID");


        log.warn("aclog_ "+jsessionid+" pay "+id);




        return RS.ok();
    }





    @RequestMapping("/dic")
    public void dic(HttpServletRequest request, HttpServletResponse response){

        OutputStream out = null;
        try {

            String filePath = "D:\\java\\nginx-1.17.8\\dic.txt";
            // 读取字典文件
            File file = new File(filePath);
            String content = "";
            if(file.exists()){
                // 读取文件内容
                FileInputStream fi = new FileInputStream(file);
                byte[] buffer = new byte[(int) file.length()];
                int offset = 0, numRead = 0;
                while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
                    offset += numRead;
                }
                fi.close();
                content = new String(buffer, "UTF-8");
            }
            // 返回数据
            out = response.getOutputStream();
            response.setHeader("Last-Modified", String.valueOf(System.currentTimeMillis()));
            response.setHeader("ETag",String.valueOf(System.currentTimeMillis()));
            response.setContentType("text/plain; charset=utf-8");
            out.write(content.getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
